package com.example.fang.demodruid.controller;

import com.example.fang.demodruid.entity.User;
import lombok.extern.slf4j.Slf4j;
import ocxbwjmjmjsfzf.SMUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @describe:
 * @author:01410843
 * @Date 2022/7/7 13:58
 **/
@RestController
@RequestMapping("/test/")
@Slf4j
public class LayuiController {

    static {
        SMUtil.setLicense("b2FPemdXcEMxWlpSNDVjUmxxU3JWK3ZhQU8zNUVVTTJZSC9kS1J4UTNEaFJvMCtOakxRbjF5d1hjeTJnRnNlZW92OU90amVydGU1aGVSTEZJTWtEL2JNai9qOThSOGhld3gwSE44OTQ3amxQS0R3bHhrQ3dyS0tCazV3OEVWV1Q3SXRqS3NhOU1NSGtmLzRiblhsT1JKOUxIWWxaMlFwV0tDS3NaYTduS3YwPXsiaWQiOjAsInR5cGUiOiJ0ZXN0IiwicGxhdGZvcm0iOjQsIm5vdGJlZm9yZSI6IjIwMjIwNjE2Iiwibm90YWZ0ZXIiOiIyMDIyMTIxNiJ9");
    }
    @RequestMapping("/add")
    public Map<String,Object> test(HttpServletRequest request,User user){
        System.out.println("成功进入方法");
        Map<String,Object> res=new HashMap<>();
        System.out.println("user"+user);
        res.put("code","10010");
        return res;
    };

    @RequestMapping("/genR0")
    public Map<String,Object> genR0(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/html");
        Map<String,Object> res=new HashMap<>();
        SMUtil smutil = new SMUtil();
        // 加密R0,r0是由加密机生成的
        String r0 = "A9AC3F9F758FE94C4BD69A318315749F";
       //服务端加密r0
        HashMap<String, String> hm = smutil.sEncryptServerRand(r0);
        String enStr = "";
        if ("0".equals(hm.get("code"))) {
            enStr = hm.get("message");
            System.out.println("r0 miwen:" + enStr);
        } else {
            System.out.println(hm.get("code") + " : " + hm.get("message"));
        }
        res.put("code",hm.get("code"));
        res.put("message",hm.get("message"));
        return res;
    };

    /**
     * @Author 01410843
     * @Description  前端加密后的数据进行解密
     * @Date 11:10 2022/7/15
     * @Param [request, response]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @RequestMapping("/decryptECB")
    public Map<String,Object> decryptECB(HttpServletRequest request, HttpServletResponse response)  throws Exception{
        Map<String,Object> res=new HashMap<>();
        response.setContentType("text/html");
        String rnpie = request.getParameter("rnpie");
        String censtr = request.getParameter("enstr");
        String pubids = request.getParameter("pubid");
        int pubid = 2;
        if (pubids != null) {
            pubid = Integer.parseInt(pubids);
        }
        SMUtil smutil = new SMUtil();
        String rn = "";
        if (rnpie != null) {
            // 解密rnpie得到rn，实际集成此步骤需要发给加密机解密
            if (pubid == 1) {
                // 此处应该发给加密机解密
                rn = smutil.decryptSM2("xxxxxxxxxxxxxxxxxxx", "04" + rnpie, 0);
            } else {
                /**
                  * decryptSM2(String pri,String enstr,int arg1);
                  * pri:SM2私钥 enstr:待解密数据，字符串类型，SM2密文，RNpie。
                  * 非H5的客户端的RNpie是报文密文的前256位，H5的客户端接口的RNpie和报文密文是两个json key值变量
                  * arg1：无意义，固定写成0
                 **/
                rn = smutil.decryptSM2("5B13F48E5BFA5F5CCE857B1819B32E7EB06E750120BEEC2957536958B938E9D6", "04" + rnpie, 0);
                //RN，字符串类型，如果解密失败，则是SM2公私钥没对应上，RN用于存入session会话或其他类似的会话中，用于后面加解密报文
            }
            // 将rn存入会话
            request.getSession().setAttribute("rn", rn);
        } else {
            rn = (String) request.getSession().getAttribute("rn");
        }
        // 服务端解密客户端报文校验Hmac
        HashMap<String, Object> hmsde = smutil.sDecryptByECBAnCheckHmac(rn, censtr, "utf-8");
        HashMap<String, String> sm4ecbde = null;
        String destr = "";
        if ("0".equals(hmsde.get("code"))){
            sm4ecbde = (HashMap<String, String>) hmsde.get("message");
            destr = sm4ecbde.get("val");
            System.out.println("decrypt str:" + destr);
            res.put("code",hmsde.get("code"));
            res.put("message",java.net.URLEncoder.encode(destr, "utf-8").replaceAll("\\+","%20"));
        }else{
            System.out.println(hmsde.get("code") + " : " + hmsde.get("message"));
            res.put("code",hmsde.get("code"));
            res.put("message",java.net.URLEncoder.encode(destr, "utf-8").replaceAll("\\+","%20"));
        }
        return res;
    }

    /**
     * @Author 01410843
     * @Description 服务端数据加密  前端解密数据
     * @Date 11:19 2022/7/15
     * @Param [request, response]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @RequestMapping("/encryptECB")
    public Map<String,Object> encryptECB(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> res=new HashMap<>();
        String rn = (String) request.getSession().getAttribute("rn");
        SMUtil smutil = new SMUtil();
        // 服务端加密报文同时做Hmac
        String bwstrs = "the银行server";
        /**
         * sEncryptServerRand(String r0); r0:32位随机数，由加密机生成
         * 返回值：code码和message，key值是code码，0表示正常，message为r0密文，其他表示错误信息
         **/
        HashMap<String, String> hmsen = smutil.sEncryptByECBAndHmac(rn, bwstrs, "utf-8");
        String senstr = "";
        if ("0".equals(hmsen.get("code"))) {
            senstr = hmsen.get("message");
            // SM4密文和Hmac密文
            System.out.println("server D|H:" + senstr);
            res.put("code",hmsen.get("code"));
            res.put("message", hmsen.get("message"));
        } else {
            System.out.println(hmsen.get("code") + " : " + hmsen.get("message"));
            res.put("code",hmsen.get("code"));
            res.put("message",hmsen.get("message"));
        }
        return  res;
    }

}
